<template>
  <!-- 商品选择组件 -->
  <div>
    <div class="margin-container-list">
      <!--顶部搜索 -->
      <div class="top-operate">
        <div class="search-item">
          <el-input @keyup.enter.native="handleSearch" v-model="searchKeyword" placeholder="商品名称"></el-input>
          <div>
            <div v-if="!this.enterpriseConfig.categorySeparate">
              <!-- 零售与批发商品分类分开设置 关闭 -->
              <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" change-on-select placeholder="选择商品分类"
                :options="categoryData" class="special-input" clearable></el-cascader>
            </div>
            <div v-else>
              <div v-if="!this.enterpriseConfig.wholesaleCategoryAlias">
                <!-- 批发商品分类使用别名 关闭 -->
                <el-cascader v-model="wholesaleCategoryIds" :props="{ checkStrictly: true }" change-on-select
                  placeholder="选择商品分类" :options="categoryData" class="special-input" clearable></el-cascader>
              </div>
              <div v-else>
                <el-cascader v-model="wholesaleCategoryIds" :props="{ checkStrictly: true }" change-on-select
                  placeholder="选择商品分类" :options="wholesaleCategoryData" class="special-input" clearable></el-cascader>
              </div>
            </div>
          </div>
          <div v-if="getVersionType() != 2">
            <el-select v-model="searchLabelType" placeholder="标签">
              <el-option v-for="(val, key) in dict.labelType" :key="key" :label="val" :value="key">
              </el-option>
            </el-select>
          </div>

          <el-button plain @click="handleSearch">查询</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </div>
        <div class="btn-search">
          <el-button @click="handleBatchSelect" type="primary">批量选择</el-button>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="goodsList" @selection-change="handleSelectionChange"
          v-loading="listLoading" element-loading-text="加载中">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column min-width="250px" label="商品">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <label><img :src="scope.row.mainImage" class="user-avatar"></label>
                <div class="font-14 pad-l-10">
                  <div>{{scope.row.title}}</div>
                  <div>
                    <div v-if="enterpriseConfig.categorySeparate">
                      <template v-if="scope.row.wholesaleCategoryName">
                        <div>
                          <span class="category-style">[{{scope.row.wholesaleCategoryName}}]</span>
                          <el-tag class="mar-l-10" size="mini" v-if="scope.row.skuFlag == 1" effect="light">多规格</el-tag>
                        </div>
                      </template>
                    </div>
                    <div v-else>
                      <template v-if="scope.row.categoryName">
                        <div>
                          <span class="category-style">[{{scope.row.categoryName}}]</span>
                          <el-tag class="mar-l-10" size="mini" v-if="scope.row.skuFlag == 1" effect="light">多规格</el-tag>
                        </div>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column v-if="goodsType == 31" width="100px" label="批发价" align="center">
            <template slot-scope="scope" v-if="scope.row.wholesalePrice">
              ￥{{scope.row.wholesalePrice}}
            </template>
          </el-table-column>
          <el-table-column v-if="goodsType == 30" width="100px" label="零售价" align="center">
            <template slot-scope="scope">
              ￥{{scope.row.sellPrice}}
            </template>
          </el-table-column>
          <el-table-column width="100px" label="库存" align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.stock <= scope.row.warnStock">
                <span style="color: #dd1100">{{scope.row.stock}}</span>
              </template>
              <template v-else>
                {{scope.row.stock}}
              </template>
            </template>
          </el-table-column>
          <el-table-column width="80px" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" plain @click="handleSelect(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>

    </div>
  </div>
</template>

<script>
  import {
    getGoodsList,
    batchCopy,
    listGoodsCategory,
    listWholesaleGoodsCategory
  } from '@/api/goods/goods'
  import {
    getDictByGroupName,
    getDictCommon
  } from '@/api/common/common'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  export default {
    props: {
      goodsType: {
        type: Number,
        default: 31
      },
      goodsSource: {
        type: String,
        default: ''
      },
      onFinish: {
        type: Function
      },
      crossBorderType: {
        type: Number,
        default: undefined
      },
      isContainsSupplyAllianceGoods: {
        type: Number,
        default: null
      }
    },
    data() {
      return {
        pageSelection: {},
        total: null,
        listLoading: true,
        searchListQuery: {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          title: ''
        },
        searchLabelType: '',
        searchKeyword: '',
        dict: {},
        categoryIds: [],
        // 选中的批发商品类目
        wholesaleCategoryIds: [],
        goodsList: [],
        comDict: {},
        // 商品的所有分类json
        categoryData: [],
        // 批发商品类目
        wholesaleCategoryData: [],
        // 系统参数
        enterpriseConfig: {
          categorySeparate: '0',
          wholesaleCategoryAlias: '0'
        }
      }
    },
    // 初始化页面
    created() {
      this.initDict()
      this.initEnterpriseConfig()
      this.listGoodsCategory()
      this.listWholesaleGoodsCategory()
      this.initGoodsList()
      this.initDictCommon()
    },
    mounted() {},
    methods: {
      initDictCommon() {
        getDictCommon().then(response => {
          this.comDict = response.data
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initGoodsList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.pageSelection = {}
        this.initGoodsList()
      },
      // 勾选
      handleSelectionChange(items) {
        if (items.length === 0) {
          this.pageSelection[this.searchListQuery.currentPage] = []
        } else {
          this.pageSelection[this.searchListQuery.currentPage] = items.map(item => item.goodsId)
        }
      },
      initDict() {
        getDictByGroupName('ProjectGoodsDTO').then(response => {
          this.dict = response.data
        })
      },
      initGoodsList() {
        if (this.searchLabelType) {
          this.searchListQuery['labelType'] = this.searchLabelType
        }

        this.searchListQuery['title'] = this.searchKeyword
        this.searchListQuery['oneCategoryId'] = ''
        this.searchListQuery['twoCategoryId'] = ''
        this.searchListQuery['threeCategoryId'] = ''
        this.searchListQuery['wholesaleOneCategoryId'] = ''
        this.searchListQuery['wholesaleTwoCategoryId'] = ''
        this.searchListQuery['wholesaleThreeCategoryId'] = ''
        const categoryIds = this.categoryIds
        const wholesaleCategoryIds = this.wholesaleCategoryIds
        if (categoryIds.length === 1) {
          this.searchListQuery['oneCategoryId'] = categoryIds[0]
        }
        if (categoryIds.length === 2) {
          this.searchListQuery['twoCategoryId'] = categoryIds[1]
        }
        if (categoryIds.length === 3) {
          this.searchListQuery['threeCategoryId'] = categoryIds[2]
        }
        if (wholesaleCategoryIds.length === 1) {
          this.searchListQuery['wholesaleOneCategoryId'] = wholesaleCategoryIds[0]
        }
        if (wholesaleCategoryIds.length === 2) {
          this.searchListQuery['wholesaleTwoCategoryId'] = wholesaleCategoryIds[1]
        }
        if (wholesaleCategoryIds.length === 3) {
          this.searchListQuery['wholesaleThreeCategoryId'] = wholesaleCategoryIds[2]
        }
        this.listLoading = true
        // 搜索状态
        this.searchListQuery['pagingStatus'] = this.pagingStatus
        this.searchListQuery.goodsTypes = this.goodsType
        if (this.goodsSource) {
          this.searchListQuery.goodsSourceList = this.goodsSource
        }
        // 跨境类型
        if (this.crossBorderType === undefined) {
          this.crossBorderType = 1
        }
        this.searchListQuery.crossBorderType = this.crossBorderType
        // 不包含的供货联盟批发模式
        this.searchListQuery.isContainsSupplyAllianceGoods = this.isContainsSupplyAllianceGoods
        getGoodsList(this.searchListQuery).then(response => {
          this.total = response.total
          const selectedIds = this.pageSelection[this.searchListQuery.currentPage]
          this.goodsList = response.records
          this.dict = response.dict
          setTimeout(() => {
            if (selectedIds && selectedIds.length > 0) {
              this.goodsList.filter(item => selectedIds.includes(item.goodsId)).forEach(row => {
                this.$refs.multipleTable && this.$refs.multipleTable.toggleRowSelection(row, true)
              })
            }
          }, 10)
          this.listLoading = false
        })
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      // 获取批发商品类目
      listWholesaleGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listWholesaleGoodsCategory(enterpriseId).then(response => {
          this.wholesaleCategoryData = response.data
        })
      },
      // 获取系统参数
      initEnterpriseConfig() {
        const enterpriseId = this.getEnterpriseId()
        getByEnterpriseId(enterpriseId).then((response) => {
          if (response.isError) return
          this.enterpriseConfig = response.data
        })
      },
      resetSearch() {
        this.pageSelection = {}
        this.searchListQuery = {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          title: ''
        }
        this.searchLabelType = ''
        this.searchKeyword = ''
        this.categoryIds = []
        this.wholesaleCategoryIds = []
        this.datePicker = []
        this.handleSearch()
      },
      handleSearch() {
        this.pageSelection = {}
        this.initGoodsList()
      },
      // 选择
      handleSelect(row) {
        this.handleBatchCopy([row.goodsId])
      },
      // 批量选择
      handleBatchSelect() {
        const allGoodsIds = []
        Object.values(this.pageSelection).forEach(goodsIds => goodsIds.forEach(goodsId => allGoodsIds.push(goodsId)))
        if (allGoodsIds.length === 0) {
          this.$message({
            type: 'error',
            message: '请勾选商品!'
          })
          return
        }
        this.handleBatchCopy(allGoodsIds)
      },
      handleBatchCopy(allGoodsIds) {
        batchCopy({
          goodsIds: allGoodsIds,
          // 复制后的商品类型
          goodsType: this.goodsType === 30 ? 31 : 30,
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          if (response.isError) return
          this.$message({
            message: '复制成功',
            type: 'success'
          })
          this.handleSearch()
          if (this.onFinish) {
            this.onFinish()
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .top-operate {
    margin-bottom: 0;
  }

  .search-item {
    display: flex;
    align-items: center;
    padding-bottom: 15px;
    border-bottom: solid 1px #E4E7ED;

    >div,
    .el-cascader {
      margin-right: 10px;
    }

    .el-input {
      width: 300px;
    }
  }

  .btn-search {
    height: 60px;
    display: flex;
    align-items: center;
  }

  .user-avatar {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  .category-style {
    color: #3abbdb;
  }
</style>
